import { Component, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { LoginService } from './../service/login.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  validateForm: FormGroup;

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      if (i) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    }

    if (this.validateForm.valid) {
      this.service.login(this.validateForm.value)
        .subscribe(res => {
          if (res.data) {
            sessionStorage.setItem('token', res.data.token);
            this.router.navigate(['/dashbord']);
          } else {
            this.msg.warning('账号密码错误', res.message);
          }
        });
    }
  }

  constructor(
    private fb: FormBuilder,
    private msg: NzMessageService,
    private router: Router,
    private service: LoginService
  ) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      remember: [true],
      type: ['b']
    });
  }

}
